package com.efei.jdbc.sql;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

public abstract class SqlCommon {

    protected SqlType sqlType;

    private List<SqlParameter> parameters = null;

    public SqlCommon(SqlType sqlType) {
        this.sqlType = sqlType;
    }


    public SqlCommon addParameters(List<SqlParameter> ps) {
        initParameters();
        for(SqlParameter p: ps) {
            parameters.add(p);
        }
        return this;
    }

    public SqlCommon addParameter(String name,Object value) {
        initParameters();
        if(name==null) {
            throw new RuntimeException("param is null");
        }
        parameters.add(new SqlParameter(name, value));
        return this;
    }

    public SqlCommon addParameter(SqlParameter p) {
        initParameters();
        if(p==null) {
            return this;
        }
        parameters.add(p);
        return this;
    }
    private synchronized  void initParameters(){
        if(parameters==null){
            parameters = new ArrayList<>();
        }
    }

    public String getParameterOfString() {
        try {
            String ss = new ObjectMapper().writeValueAsString(parameters);
            return ss;
        } catch (JsonProcessingException e1) {
            // TODO Auto-generated catch block
            throw new RuntimeException(e1);
        }
    }
    public static SqlSelect select(){
        return new SqlSelect();
    }

    public static SqlInsert insert(){
        return new SqlInsert();
    }

    public static SqlUpdate update(){
        return new SqlUpdate();
    }

    public static SqlDelete delete(){
        return new SqlDelete();
    }

    public abstract StringBuilder getSql();
}
